package com.how2java.tmall.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.how2java.tmall.mapper.PropertyvalueMapper;
import com.how2java.tmall.pojo.Product;
import com.how2java.tmall.pojo.Property;
import com.how2java.tmall.pojo.Propertyvalue;
import com.how2java.tmall.service.PropertyService;
import com.how2java.tmall.service.PropertyValueService;

@Service
public class PropertyValueServiceImpl implements PropertyValueService {

	@Autowired
	private PropertyvalueMapper propertyValueMapper;
 
    @Autowired
    private PropertyService propertyService;
	
	@Override
	public void init(Product p) {
		List<Property> pts = propertyService.list(p.getCid());
		
		for (Property pt: pts) {
            Propertyvalue pv = this.get(pt.getId(),p.getId());
            if(null==pv){
                pv = new Propertyvalue();
                pv.setPid(p.getId());
                pv.setPtid(pt.getId());
                propertyValueMapper.insert(pv);
            }
        }
	}

	@Override
	public void update(Propertyvalue pv) {
		propertyValueMapper.updateByPrimaryKeySelective(pv);
	}
	
	/**
	 * 根据产品id和属性id获取属性值对象
	 */
	@Override
    public Propertyvalue get(int ptid, int pid) {
        List<Propertyvalue> pvs= propertyValueMapper.getListByPtidAndPid(ptid,pid);
        if (pvs.isEmpty())
            return null;
        return pvs.get(0);
    }
	
	/**
	 * 根据产品id获取其所有的属性值集合
	 */
	@Override
	public List<Propertyvalue> list(int pid) {
        List<Propertyvalue> result = propertyValueMapper.getListByPid(pid);
        for (Propertyvalue pv : result) {
            Property property = propertyService.get(pv.getPtid());
            pv.setProperty(property);
        }
        return result;
	}

}
